import express, { Express } from 'express'
import cors from 'cors'
import helmet from 'helmet'
import dotenv from 'dotenv'
import { createServer } from 'http'
import { testConnection } from './utils/database'
import { requestLogger, errorHandler, notFoundHandler } from './middleware/errorHandler'
import apiRoutes from './routes'
import { groupingService } from './services/groupingService'

// 加载环境变量
dotenv.config()

// 直接设置环境变量（如果未设置）
if (!process.env.DATABASE_URL) {
  process.env.DATABASE_URL = 'mysql://dx_user:xie500qiang200@localhost:3306/dx_fun_group'
}

// 调试信息
console.log('🔧 环境变量调试信息:')
console.log('NODE_ENV:', process.env.NODE_ENV)
console.log('PORT:', process.env.PORT)
console.log('DATABASE_URL:', process.env.DATABASE_URL ? '已设置' : '未设置')

const app: Express = express()
const server = createServer(app)
const PORT: number = parseInt(process.env.PORT || '3000', 10)

// 请求日志中间件
if (process.env.NODE_ENV === 'development') {
  app.use(requestLogger)
}

// 安全中间件
app.use(helmet())

// CORS 配置
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:5173'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}))

// 请求解析中间件
app.use(express.json({ limit: '10mb' }))
app.use(express.urlencoded({ extended: true, limit: '10mb' }))

// 健康检查
app.get('/health', async (_req, res) => {
  try {
    await testConnection()
    res.json({
      status: 'ok',
      timestamp: new Date().toISOString(),
      service: 'dx-fun-group-backend',
      version: '1.0.0',
      database: 'connected',
      uptime: process.uptime()
    })
  } catch (error) {
    res.status(503).json({
      status: 'error',
      timestamp: new Date().toISOString(),
      service: 'dx-fun-group-backend',
      version: '1.0.0',
      database: 'disconnected',
      error: 'Database connection failed'
    })
  }
})

// API 路由
app.use('/api', apiRoutes)

// 404 处理
app.use(notFoundHandler)

// 全局错误处理
app.use(errorHandler)

// 初始化WebSocket服务
groupingService.initialize(server)

// 启动服务器
if (process.env.NODE_ENV !== 'test') {
  server.listen(PORT, () => {
    console.log(`🚀 服务器启动成功！`)
    console.log(`🌐 访问地址: http://localhost:${PORT}`)
    console.log(`📖 健康检查: http://localhost:${PORT}/health`)
    console.log(`🔌 WebSocket: ws://localhost:${PORT}`)
    console.log(`🔧 环境: ${process.env.NODE_ENV || 'development'}`)
  })
}

export default app
